#!/bin/bash

# Java程序的绝对路径
JAVA_JAR_PATH="/home/yu/Desktop/java.jar"
# 重启尝试次数（这个变量将在cron中每次运行时重置）
RESTART_ATTEMPTS=0
# 最大重启尝试次数
MAX_RESTART_ATTEMPTS=3
# 重启检查间隔时间（秒）
SLEEP_DURATION=5

# 检查Java程序的文件是否存在
if [ ! -f "$JAVA_JAR_PATH" ]; then
    echo "$(date) - $JAVA_JAR_PATH does not exist. Sending email."
    ~/sendemail.sh
    exit 1
fi

# 检查Java程序是否在运行
if pgrep -f $JAVA_JAR_PATH > /dev/null; then
    echo "$(date) - $JAVA_JAR_PATH is running."
else
    echo "$(date) - $JAVA_JAR_PATH is not running. Attempting to restart..."

    # 尝试启动Java程序
    nohup java -jar $JAVA_JAR_PATH > /dev/null 2>&1 &

    # 等待一段时间后检查Java程序是否成功启动
    for (( ATTEMPT=1; ATTEMPT<=MAX_RESTART_ATTEMPTS; ATTEMPT++ )); do
        sleep $SLEEP_DURATION
        if pgrep -f $JAVA_JAR_PATH > /dev/null; then
            echo "$(date) - $JAVA_JAR_PATH started successfully on attempt $ATTEMPT."
            break
        else
            let RESTART_ATTEMPTS+=1
            echo "$(date) - Failed to start $JAVA_JAR_PATH. Attempt $RESTART_ATTEMPTS."
        fi
    done

    # 如果重启尝试次数超过最大限制，则停止监控并发送邮件
    if [ "$RESTART_ATTEMPTS" -ge "$MAX_RESTART_ATTEMPTS" ]; then
        echo "$(date) - $JAVA_JAR_PATH failed to start after $MAX_RESTART_ATTEMPTS attempts. Stopping monitoring and sending email."
        ~/sendemail.sh
        exit 1
    fi
fi